<script setup lang="tsx">
import { ref, computed, reactive } from 'vue'
import { ElLoading, ElMessage, ElIcon } from 'element-plus'
import {
  adminBusinessSubsidyPreRechargeApi,
  adminBusinessSubsidyRechargeApi,
  adminBusinessRechargeApplyApi
} from '@/api/MerchantAccount'
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { Plus } from '@element-plus/icons-vue'
import { uploadFileApi } from '@/api/common'

const emits = defineEmits(['close'])

const { required } = useValidator()

const props = defineProps({
  type: {
    type: Number,
    default: 0
  }
})
console.log(props.type)

const formData = ref({
  payType: '2' // 支付方式(1-微信，2-网银对公)
})

// 充值金额(手动输入金额，不包含12元手续费)
const rechargeAmt = ref()

// 待支付金额，含手续费12
const payAmt = computed(() => {
  return rechargeAmt.value
    ? +rechargeAmt.value + ((detailInfo.value && detailInfo.value.bankFeeAmt) || 0)
    : 0
})

const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)
const dialogVisible3 = ref(false)

const toPay = async () => {
  if (!rechargeAmt.value) {
    ElMessage.error('请输入充值金额')
    return
  } else if (+rechargeAmt.value < 1) {
    ElMessage.error('充值金额不能小于1元')
    return
  }

  const loadingInstance = ElLoading.service({ fullscreen: true })
  try {
    adminBusinessSubsidyRechargeApi({
      rechargeAmt: +rechargeAmt.value
    })
      .then((res: any) => {
        if (res.code === 200) {
          window.open(res.data.fromUrl, '_blank')
          emits('close', { payAmt: payAmt })
        } else {
          ElMessage.error(res.message)
        }
      })
      .finally(() => {
        loadingInstance.close()
      })
  } catch (error) {
    loadingInstance.close()
  }
}

const detailInfo = ref()

const getDetail = async () => {
  const res = await adminBusinessSubsidyPreRechargeApi()
  detailInfo.value = res.data
}

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const imageUrl = ref('')
const schema = reactive<FormSchema[]>([
  {
    field: 'paymentNo',
    label: '打款单号',
    colProps: {
      span: 24
    },
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'tradeAmt',
    label: '打款金额',
    colProps: {
      span: 24
    },
    component: 'InputNumber',
    componentProps: {
      controls: false,
      precision: 2
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'paymentImage',
    label: '打款凭证',
    colProps: {
      span: 24
    },
    component: 'Upload',
    componentProps: {
      action: '#',
      showFileList: false,
      httpRequest: async (e) => {
        const formData = new FormData()
        formData.append('file', e.file)
        const res = await uploadFileApi(0, formData)
        imageUrl.value = res.data
        setValues({ paymentImage: res.data })
      },
      slots: {
        default: () => (
          <>
            {imageUrl.value ? <img src={imageUrl.value} class="avatar" /> : null}
            {!imageUrl.value ? (
              <ElIcon class="avatar-uploader-icon" size="large">
                <Plus />
              </ElIcon>
            ) : null}
          </>
        )
      }
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'remark',
    label: '备注',
    colProps: {
      span: 24
    },
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 2
    }
  }
])

const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const loadingInstance = ElLoading.service({ fullscreen: true })
    const formData = await getFormData()
    adminBusinessRechargeApplyApi(formData)
      .then((res) => {
        if (res.code === 200) {
          reset()
          emits('close')
        } else {
          ElMessage.error(res.message)
        }
      })
      .finally(() => {
        loadingInstance.close()
      })
  }
}

// 重置Form
const reset = async () => {
  const elForm = await getElFormExpose()
  setValues({})
  elForm?.resetFields()
}

onMounted(() => {
  getDetail()
})
</script>

<template>
  <div v-if="detailInfo">
    <div class="mb-30px">
      <div class="text-2xl">{{ detailInfo.subsidyAmt }}</div>
      <div>补贴账户余额</div>
    </div>
    <div class="flex mb-20px text-lg">
      <div class="inline-flex flex-col w-1/4">
        <div>{{ detailInfo.waitRechargeAmt }}</div>
        <div class="box flex items-center text-gray-400 text-sm">
          <span>待充值</span>
          <div
            class="flex items-center ml-1 w-[13px] h-[13px] font-bold text-12px circle-icon circle-icon1"
            @click="dialogVisible1 = true"
            >?</div
          >
          <div class="tooltip-content tooltip-content1">
            <div class="title">待充值</div>
            <div class="desc">已结算待打款的补贴金额-补贴账户余额</div>
          </div>
        </div>
      </div>
      <div class="inline-flex flex-col w-1/4">
        <div>{{ detailInfo.monthWaitSettleAmt }}</div>
        <div class="box flex items-center text-gray-400 text-sm">
          <span>本月待结算</span>
          <div
            class="flex items-center ml-1 w-[13px] h-[13px] font-bold text-12px circle-icon circle-icon2"
            @click="dialogVisible2 = true"
            >?</div
          >
          <div class="tooltip-content tooltip-content2">
            <div class="title">本月待结算</div>
            <div class="desc">本月已核销订单，需要补贴给商户的金额</div>
          </div>
        </div>
      </div>
      <div class="inline-flex flex-col w-1/4">
        <div>{{ detailInfo.lastMonthSettleAmt }}</div>
        <div class="box flex items-center text-gray-400 text-sm">
          <span>上月结算</span>
          <div
            class="flex items-center ml-1 w-[13px] h-[13px] font-bold text-12px circle-icon circle-icon3"
            @click="dialogVisible3 = true"
            >?</div
          >
          <div class="tooltip-content tooltip-content3">
            <div class="title">上月结算</div>
            <div class="desc">上个自然月实际结算打款给商户的补贴金额</div>
          </div>
        </div>
      </div>
    </div>
    <div class="bg-gray-200 px-5px py-10px mb-20px text-sm">
      每月1号结算上个自然月商户补贴提现总额，根据实际划拨金额收取2%营销服务费，并开回6%的增值税发票。合计费率<span
        class="text-red-600"
        >8%</span
      >，请保证充值金额包含8%服务费用，否则将影响商户提现。
    </div>
    <div class="flex justify-end mb-20px">
      <div class="inline-flex flex-col">
        <div class="flex justify-between"
          ><div class="min-w-110px text-right">待充值金额：</div
          ><div class="min-w-100px text-right text-red-600"
            >¥{{ detailInfo.waitRechargeAmt }}</div
          ></div
        >
        <div class="flex justify-between mt-2"
          ><div class="min-w-110px text-right">服务费金额：</div
          ><div class="min-w-100px text-right text-red-600">¥{{ detailInfo.feeAmt }}</div></div
        >
        <div class="flex justify-between mt-2"
          ><div class="min-w-110px text-right">发票税点金额：</div
          ><div class="min-w-100px text-right text-red-600">¥{{ detailInfo.invoiceAmt }}</div></div
        >
        <div class="flex justify-between mt-6"
          ><div class="min-w-110px text-right">合计待充金额：</div
          ><div class="min-w-100px text-right text-red-600"
            >¥{{ detailInfo.totalWaitRechargeAmt }}</div
          ></div
        >
        <div v-if="type === 1" class="w-full flex justify-end mt-2">
          <input
            class="h-7 w-full"
            v-model="rechargeAmt"
            type="number"
            placeholder="请输入充值金额"
          />
        </div>
      </div>
    </div>
    <template v-if="type === 2">
      <div class="mb-10px font-bold">收款信息</div>
      <div class="flex text-14px py-2">
        <div class="flex flex-[50%]">
          <span>收款人名称：</span>
          <span>厦门火动通告科技有限公司</span>
        </div>
        <div class="flex flex-[50%]">
          <span>收款人账号：</span>
          <span>592908801410401</span>
        </div>
      </div>
      <div class="flex text-14px py-2">
        <span>收款人开户行：</span>
        <span>招商银行股份有限公司厦门软件园支行</span>
      </div>
      <div class="my-10px font-bold">打款信息</div>
      <Form @register="formRegister" :schema="schema" />
      <div class="flex flex-col justify-end items-end">
        <el-button type="danger" @click="save">提交</el-button>
      </div>
    </template>
    <template v-else>
      <div class="mb-10px">支付方式</div>
      <div class="text-sm flex items-center"
        ><img
          class="w-[15px] h-[15px] mr-2"
          src="@/assets/imgs/icon-warning.png"
        />补贴账户充值请使用<span class="text-red-600">公对公转账</span
        >，个人对公转账不支持开具费用发票。</div
      >
      <div>
        <el-radio-group v-model="formData.payType">
          <el-radio label="2">网银打款</el-radio>
        </el-radio-group>
        <div class="text-xs">（每笔收取{{ detailInfo.bankFeeAmt }}元手续费）</div>
      </div>
      <div class="flex flex-col justify-end items-end">
        <el-button
          style="height: 70px; padding: 0 50px; line-height: 70px"
          type="danger"
          @click="toPay"
        >
          <div class="flex flex-col text-xs py-4">
            <div
              ><span>¥</span><span class="text-[25px]">{{ payAmt }}</span
              >（含手续费）</div
            >
            <div class="text-lg">立即支付</div>
          </div>
        </el-button>
      </div>
    </template>
  </div>
</template>

<style scoped lang="less">
:deep(img.avatar) {
  width: 178px;
}

:deep(.el-upload) {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

:deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
